$(document).ready(function() {
	
	
});

/**
 * This file contains javascript to handle information of sale program.
 */
//////////////////////// LOADING A PAGE ////////////
function loadPage(sourceDiv, actionURL, serviceId) {
      
    $.ajax ({       
        url:        actionURL + "?set_ajax_view",
        data:       "service_id=" + serviceId,      
        dataType:   "html",
        beforeSend: function() {
            $('div#pageContent').hide("slow");
            $('div#' + sourceDiv).hide("slow");         
        },
        complete:   function() {
            $('div#' + sourceDiv).show("fast");
        },
        success:  function(data) {
            $("#" + sourceDiv).html(data);
        }
    });
}

// 'serviceArray' is used to add/ remove service. This variable is initialized 
// when an item of 'sale_program' listbox is selected.
var serviceArray = new Array();

// Load the list of mapped service of the specific sale program.
function loadMappedService() {
    $.ajax ({       
        url:        "LoadMappedServiceAjax?set_ajax_view",
        data:       "sale_program_id=" + $('#sale_program option:selected').val(),
        dataType:   "json",
        success:  function(data) {
            table = $('#mapped_service_list');
            fillTableData(table, data.body);
            
            // INIT ROOM ARRAY  
            serviceArray = new Array();
	        $('#mapped_service_list tbody').children().each(function() {      
	            serviceArray.push($(this).attr('id'));         
	        });
	    }
    });
}

function fillTableData(table, data) {
    $('tbody', table).children().remove();
    $('tbody', table).append(data);
}

// Add service into the mapped service list of current sale program
function addService() {

	//#0 Reset warning status
	$('span#status_message').html('');
	$('#serviceList').css('border-color', '#AAA');
	$('#serviceGroup').css('border-color', '#AAA');
	$('#discount').css('border-color', '#AAA');

	//#1 Validate serviceGroup
	if ( $('#serviceGroup').val() == "" ) {
		$('span#status_message').text(_('Please select service group.')).show();
		$('#serviceGroup').css('border-color', 'red');
		return;
	}

	var services = $('tr#services option:selected');

	//#2 Validate services
	if (services.length == 0)
	{
		$('span#status_message').text(_('Please select service.')).show();
		$('#serviceList').css('border-color', 'red');
		return;
	}
	
	var _serviceIds = new Array();
	var _serviceNames = new Array();
	var existedIndex = new Array();
	
	//#3 Check if this service is existed in the service list     
	for(i = 0; i < services.length; i++)
	{
		var serviceId = services[i].value;
		var serviceName = services[i].text;
    	
	    if ($.inArray(serviceId, serviceArray) >= 0) {
	    	existedIndex.push(i);
	        
	    } else {
			_serviceIds.push(serviceId);
			_serviceNames.push(serviceName);
	    }
    	
	}

	if(existedIndex.length > 0)
	{
		var existedServiceName = _("Existed: ");		
		for(i = 0; i < existedIndex.length; i++)
		{
			var index = existedIndex[i];
			var serviceName = services[index].text;
			
			existedServiceName +=  serviceName;
			
			if (i != existedIndex.length - 1) {
				existedServiceName += '; ';
			}
			
		}
		
		//$.prompt('Existed: <br>' + existedServiceName);
		$('span#status_message').text(existedServiceName).show();
		$('#serviceList').css('border-color', 'red');
		
		return;
	}
	
	if (_serviceIds.length == 0){
		return;
		
	}
	
	//#4 validate value for discount
    if (!isNotEmpty($('#discount'), _("Empty discount value"), "status_message")) {
        return;
        
    }
    
    //#5 check if percent or currency is checked
    var discount = $('#discount').val();
    
    var _percent = "";
    var _currency = "";
    if($('#percent:checked').val() == "yes")
    {
    	_percent = ' checked="checked"';
    	errMessage = _('Discount percent must be between 0% and 100%');
    	if(!checkNumberInRange($('#discount'), 0, 100, errMessage, 'status_message', '#AAA')){
        	return;
    	}
    } else {
    	_currency = ' checked="checked"';
    	
    }
    
    // add these services into the services list
    for(i = 0; i < _serviceIds.length; i++)
	{
		var serviceId = _serviceIds[i];
    	var serviceName = _serviceNames[i];
    	
    	var valueId = 'value_' + serviceId;
	    var percentId = 'percent_' + serviceId;
	    var html = '<tr id="' + serviceId + '">'
	             + '<td>'
	             +     '<input type="hidden" id="serviceId[]" value="' + serviceId + '">'
	             +     '<span>' + serviceName + '</span>'
	             + '</td>'
	             + '<td>'
	             +     '<input value="' + discount + '" id="' + valueId + '" name="' + valueId + '" type="text" onkeyup="javascript:this.value=this.value.replace(/[^0-9]/g, \'\');">'
	             + '</td>'
	             + '<td>'
	             +     '<input type="radio" id="' + percentId + '" name="' + percentId + '" value="yes"' + _percent + '>%'
	             +     '<input type="radio" id="' + percentId + '" name="' + percentId + '" value="no"' + _currency + '>' + _('VND') 
	             + '</td>'
	             + '<td>'
	             +     '<a href="javascript:removeService(' + serviceId + ');" title="' + _("Delete service") + '">' 
	             +         '<img src="../images/remove_small.png" alt="' + _("Delete") + '"></img>'
	             +     '</a>'
	             + '</td>'
	             + '</tr>';
	    $('tbody', $('#mapped_service_list')).append(html);
	    serviceArray.push(serviceId);
	            
	    $('#mapped_service_list tr').removeClass('alt');
	    $('#mapped_service_list tr:even').addClass('alt');
	    $('#mapped_service_list').show();
    	
	}
	 
}

// Remove service from the mapped service list of current sale program
function removeService(serviceId) {
    $('#mapped_service_list tr#' + serviceId).nextAll().toggleClass('alt');
    $('#mapped_service_list tr#' + serviceId).remove();
    
    //Remove serviceId from serviceArray
    var temp = new Array();
    for(i = 0; i < serviceArray.length; i++)
    {
    	if (serviceArray[i] != serviceId)
    	{
    		temp.push(serviceArray[i]);
    	}	
    }
    serviceArray = temp ;
    
    if ($('#mapped_service_list tbody tr').length == 0) {
        $('#mapped_service_list').hide('medium');
    } 
}

// Save the mapping of sale program and service
function saveSaleService() {
    // refresh status_message
    $('#status_message').html("");
    
    // prepare data before saving
    var saleServiceArr = new Array();   
    for (var i = 0; i < serviceArray.length; i++){
        // validate value for sale_service
        if (!isNotEmpty($('#value_' + serviceArray[i]), _("Empty discount value"), "status_message")) {
            return;
        }
        if($("input:radio\[name=\'percent_" + serviceArray[i] + "\'\]:checked").val() == 'yes'){
        	_percent = ' checked="checked"';
        	errMessage = _('Discount percent must be between 0% and 100%');
        	if(!checkNumberInRange($('#value_' + serviceArray[i]), 0, 100, errMessage, 'status_message', '#AAA')){
            	return;
        	}
        }
        // 'obj' contains serviceId, value, percent
        var obj = new Array();
        obj[0] = serviceArray[i];
        obj[1] = $('#value_' + serviceArray[i]).val();
        obj[2] = $("input:radio\[name=\'percent_" + serviceArray[i] + "\'\]:checked").val();
        
        saleServiceArr.push(obj);
    }
    // call controller to save data
    $.ajax({
        type:   "POST",
        url:    "../SaleProgram/SaveSaleServiceAjax?set_ajax_view",
        data:   "sale_program_id=" + $('#sale_program option:selected').val() +
                "&sale_service_array=" + saleServiceArr.join(';'),
        beforeSend: function() {
            $('#btn_save').hide();
            $('#barLoading').show();                
        },
        complete:   function() {
            $('#btn_save').show();
            $('#barLoading').hide();
        },
        success:    function(data) {
        
        }
    });
}

function saveSaleProgram() {
    
    // refresh status_message
    $('#status_message').html("");
    // prepare data before saving
    
    // check sale_program_name
    if (!isNotEmpty($('#name'), _("Empty promotion program name"), "status_message")) {
        return;
    }
    
    // check sale_program_code
    if (!isNotEmpty($('#code'), _("Empty promotion program code"), "status_message")) {
        return;
    }
    
  

	$.ajax({
        type:   "GET",
        url:    "../SaleProgram/CheckSaleProgramCode?set_ajax_view",
        data:   'code=' + $('#code').val() +
        		'&sale_program_id=' + $('#sale_program_id').val() ,        
        success:    function(data) {
        	if (data == 1) {
        		submitSave();
        	} else if (data == 0) {
        		$('#status_message').text(_('Duplicated promotion program code')).show();
				$('#code').css("border-color", "red");
        	}        	
        }
    });
    
	
	
    
}

function submitSave() {
	var submitData = $('#add_sale_program_form').formSerialize();
    // call controller to save data
    $.ajax({
        type:   "POST",
        url:    "../SaleProgram/SaveSaleProgramAjax?set_ajax_view",
        data:   submitData,
        beforeSend: function() {
            $('div#list_sale_program_container').hide();
            $('#barLoading').show();                
        },
        complete:   function() {
            $('#barLoading').hide();
            
        },
        success:    function(data) {        	
        	loadPage('pageContent', 'ListSaleProgram', '');
        }
    });
}

function editSaleProgram(sale_program_id, name, description, code){
	$('div#add_form').fadeOut("fast");
	$('#status_message').text('').hide();
	$('#name').css("border-color", "#AAA");
	$('#description').css("border-color", "#AAA");
	$('#code').css("border-color", "#AAA");
	$('#sale_program_id').val(sale_program_id);
	$('#name').val(name);
	$('#description').val(description);
	$('#code').val(code);
	
	$('#button_add').hide();
	$('#button_save').show();
	$('#button_cancel').show();
	$('div#add_form').fadeIn("slow");
	window.scrollTo(0,0);
}

function cancelSaleProgram() {
	$('div#add_form').fadeOut("fast");
	$('#status_message').text('').hide();
	$('#name').css("border-color", "#AAA");
	$('#description').css("border-color", "#AAA");
	$('#code').css("border-color", "#AAA");
	$('#sale_program_id').val('');
	$('#name').val('');
	$('#description').val('');
	$('#code').val('');
	
	$('#button_add').show();
	$('#button_save').hide();
	$('#button_cancel').hide();
	$('div#add_form').fadeIn("slow");
}
function cancelSaleProgramStore() {
	$('div#edit_form').fadeOut("fast");
	$('div#add_form').fadeIn("slow");
}

function addSaleProgramStore(){
	$('#status_message_add').hide();
	if (!checkMonth($('#start_mm'),true,'','status_message_add')) {
		$('#status_message_add').show();
		return;
	} 
	
	if (!checkDay($('#start_dd'),true,'','status_message_add')) {
		$('#status_message_add').show();	
		return;
	}	
	var res 	= 	checkDate($('#start_yyyy'),$('#start_mm'),$('#start_dd'), true, '', 'status_message_add', false);
	if(!res){	
		$('#status_message_add').show();
		return ;
	}
	
	if (!checkMonth($('#end_mm'),true,'','status_message_add')) {
		$('#status_message_add').show();
		return;
	} 
	
	if (!checkDay($('#end_dd'),true,'','status_message_add')) {
		$('#status_message_add').show();	
		return;
	}	
	var res 	= 	checkDate($('#end_yyyy'),$('#end_mm'),$('#end_dd'), true, '', 'status_message_add', false);
	if(!res){	
		$('#status_message_add').show();
		return ;
	}
	
	
	var startday = $.trim($('#start_dd').val());
	var startmonth = $.trim($('#start_mm').val());
	var startyear = $.trim($('#start_yyyy').val());	
	var start = startday + "/" + startmonth + "/" + startyear;
	
	var endday = $.trim($('#end_dd').val());
	var endmonth = $.trim($('#end_mm').val());
	var endyear = $.trim($('#end_yyyy').val());
	var end = endday + "/" + endmonth + "/" + endyear;
	
	// check start_date field
	
	if(compareDate(start,end) == 'gt') {
		$('#status_message_add').text(_('Start date must be before end date')).show();
		return;
	} 	
	var submitData = $('#add_sale_program_store_form').formSerialize();	
	$.ajax({
        type:   "POST",
        url:    "../SaleProgram/SaveSaleProgramStoreAjax?set_ajax_view",
        data:   submitData,
        beforeSend: function() {
            
           $('#barLoading').show();               
        },
        complete:   function() {
            $('#barLoading').hide();
            
        },
        success:    function(data) {        	
        	loadPage('pageContent', 'ListAliveSaleProgramAjax', '');
        }
    });


}

function editSaleProgramStore(sale_program_store_id, name,  start_date, end_date, datepart0, datepart1, datepart2){
	var startArr = start_date.split("/");
	var endArr = end_date.split("/");
	
	$('div#add_form').fadeOut("fast");
	$('#sale_program_store_id').val(sale_program_store_id);
	$('#name').val(name);
	$('#edit_start_' + datepart0).val(startArr[0]);
	$('#edit_start_' + datepart1).val(startArr[1]);
	$('#edit_start_' + datepart2).val(startArr[2]);
	
	$('#edit_end_' + datepart0).val(endArr[0]);
	$('#edit_end_' + datepart1).val(endArr[1]);
	$('#edit_end_' + datepart2).val(endArr[2]);
	
	$('div#edit_form').fadeIn("slow");
	
	window.scrollTo(0,0);
}

function saveSaleProgramStore(){
	if (!checkMonth($('#edit_start_mm'),true,'','status_message_edit')) {
		return;
	} 
	
	if (!checkDay($('#edit_start_dd'),true,'','status_message_edit')) {	
		return;
	}	
	var res 	= 	checkDate($('#edit_start_yyyy'),$('#edit_start_mm'),$('#edit_start_dd'), true, '', 'status_message_edit', false);
	if(!res){
		return ;
	}
	
	if (!checkMonth($('#edit_end_mm'),true,'','status_message_edit')) {
		return;
	} 
	
	if (!checkDay($('#edit_end_dd'),true,'','status_message_edit')) {	
		return;
	}	
	var res 	= 	checkDate($('#edit_end_yyyy'),$('#edit_end_mm'),$('#edit_end_dd'), true, '', 'status_message_edit', false);
	if(!res){
		return ;
	}
	
	
	var startday = $.trim($('#edit_start_dd').val());
	var startmonth = $.trim($('#edit_start_mm').val());
	var startyear = $.trim($('#edit_start_yyyy').val());	
	var start = startday + "/" + startmonth + "/" + startyear;
	
	var endday = $.trim($('#edit_end_dd').val());
	var endmonth = $.trim($('#edit_end_mm').val());
	var endyear = $.trim($('#edit_end_yyyy').val());
	var end = endday + "/" + endmonth + "/" + endyear;
	
	// check start_date field
	
	if(compareDate(start,end) == 'gt') {
		$('#status_message_edit').text(_('Start date must be before end date')).show();
		return;
	} 			
	$('#status_message_edit').text('');
	var submitData = $('#edit_sale_program_store_form').formSerialize();
	$.ajax({
        type:   "POST",
        url:    "../SaleProgram/SaveSaleProgramStoreAjax?set_ajax_view",
        data:   submitData,
        beforeSend: function() {
            
           $('#barLoading').show();               
        },
        complete:   function() {
            $('#barLoading').hide();
            
        },
        success:    function(data) {
        	loadPage('pageContent', 'ListAliveSaleProgramAjax', '');
        }
    });
}
		
function getServices(){
	$('#status_message').html("");
	$('#serviceGroup').css("border-color", "#AAA");

	$.ajax({
        type:   "GET",
        url:    "../ServiceGroup/GetServicesByIdAjax?set_ajax_view",
        data:   "&groupId=" + $('#serviceGroup').val(),
        beforeSend: function() {
			$('#addService').hide();
			$('#serviceBarLoading').show();
			
        },
        complete:   function() {
            $('tr#services').show("fast");
            $('#addService').show();
            $('#serviceBarLoading').hide();
            
        },
        success:    function(data) {
        	$('tr#services').html(data);
        }
    });
	
}	






